﻿package com.lic.finance.xml;

import com.lic.finance.po.OutgoItem;
import com.lic.finance.utils.Util;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class XMLUtils {

	private Document doc;

	public XMLUtils(String filePath) {
		try {
			File file = new File(filePath);
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			doc = builder.parse(file);
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	public String[] getAttrValues(String tagname, String attrName) {
	    NodeList nodeList = doc.getElementsByTagName(tagname);
	    String[] attrValues = null;
	    if (nodeList.getLength() > 0) {
	        attrValues = new String[nodeList.getLength()];
	        NamedNodeMap attrs = null;
	        for(int i = 0; i < nodeList.getLength(); i++) {
	            attrs = nodeList.item(i).getAttributes();
	            Node node = attrs.getNamedItem(attrName);
	            if (node != null) {
	                attrValues[i] = node.getNodeValue();
	            }
	        }
	    } else {
	        System.out.println("Do not find any tag named : " + tagname);
	    }

	    return attrValues;
	}

	/**
     * Get out go items.
     *
     * @param transType 1收入2支出4转帐
     * @return
     */
    public List<OutgoItem> getOutgoItems(int transType) {
        boolean dropNode = false;
        List<OutgoItem> list = new ArrayList<OutgoItem>();
        NodeList nodeList = doc.getElementsByTagName("TRANS");
        NamedNodeMap attrs = null;
        for(int i = 0; i < nodeList.getLength(); i++) {
            dropNode = false;
            OutgoItem item = new OutgoItem();
            attrs = nodeList.item(i).getAttributes();
            for(int j = 0; j < attrs.getLength(); j++) {
                Node node = attrs.item(j);
                if (node.getNodeName().equals("TRANSDATE"))
                    item.setDate(Util.getDate(node.getNodeValue(), Util.DATAFORMAT_STR));
                else if (node.getNodeName().equals("TRANSTYPE")) {
                    if (Integer.parseInt(node.getNodeValue()) != transType){
                        dropNode = true;
                        continue;
                    } else {
                        item.setTransType(node.getNodeValue());
                    }
                } else if (node.getNodeName().equals("PERSON"))
                    item.setPerson(node.getNodeValue());
                else if (node.getNodeName().equals("DESCRIPTION"))
                    item.setDescription(node.getNodeValue());
            }

            if (!dropNode) {
                Node nodeSibling = nodeList.item(i).getFirstChild().getNextSibling();
                attrs = nodeSibling.getAttributes();
                for (int k = 0; k < attrs.getLength(); k++) {
                    Node node = attrs.item(k);
                    if (node.getNodeName().equals("ACCTNAME"))
                        item.setAccount(node.getNodeValue());
                    else if (node.getNodeName().equals("CATEGORY"))
                        item.setCategory(node.getNodeValue());
                    else if (node.getNodeName().equals("AMOUNT"))
                        item.setAmount(Double.valueOf(node.getNodeValue()));
                }

                list.add(item);
            }
        }

        return list;
    }

	 /*
     * 打印 DOM 节点
     * 输出格式为：
     *     nodeType(nodeName,nodeValue)
     *         "ATTRIBUTE"(attributeName=attributeValue)
     *         ...
     *         childNodeType[childNodeName,childNodeValue]
     *         ...
     */
    public static void printNode(Node node,int count) {
    	//System.out.println("printNode() doc " + node);
        if (node != null) {
            String tmp = "";
            for(int i = 0 ; i < count ; i++) tmp += "  ";
            //获取node节点的节点类型，赋值给nodeType变量
            int nodeType = node.getNodeType();
            switch (nodeType) {
                case Node.ATTRIBUTE_NODE: tmp += "ATTRIBUTE";break;
                case Node.CDATA_SECTION_NODE: tmp += "CDATA_SECTION";break;
                case Node.COMMENT_NODE:tmp += "COMMENT";break;
                case Node.DOCUMENT_FRAGMENT_NODE:tmp += "DOCUMENT_FRAGMENT";break;
                case Node.DOCUMENT_NODE:tmp += "DOCUMENT";break;
                case Node.DOCUMENT_TYPE_NODE:tmp += "DOCUMENT_TYPE";break;
                case Node.ELEMENT_NODE:tmp += "ELEMENT";break;
                case Node.ENTITY_NODE:tmp += "ENTITY";break;
                case Node.ENTITY_REFERENCE_NODE:tmp += "ENTITY_REFERENCE";break;
                case Node.NOTATION_NODE:tmp += "NOTATION";break;
                case Node.PROCESSING_INSTRUCTION_NODE:tmp += "PROCESSING_INSTRUCTION";break;
                case Node.TEXT_NODE:tmp += "TEXT";break;
                default:return;//invalid node type.
            }

            System.out.println(tmp+" ("+node.getNodeName()+","+node.getNodeValue()+")");
            /*
             * node.getAttributes()方法返回
             * 包含node节点的属性的 NamedNodeMap（如果它是 Element）
             */
            NamedNodeMap attrs = node.getAttributes();
            if(attrs != null)
                for(int i = 0 ; i < attrs.getLength() ; i++){
                    printNode(attrs.item(i),count+1);
            }
            /*
             * node.getChildNodes()方法返回
             * 包含node节点的所有子节点的 NodeList。
             */
            NodeList childNodes = node.getChildNodes();
            for(int i = 0 ; i < childNodes.getLength() ; i++){
                printNode(childNodes.item(i),count+1);
            }
        }
    }
}
